/*
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: TradeFragmentPresenter.java
 *   @Date: 18-11-29 下午4:05
 *   @Author: ppzhao
 *   @Description:
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 */

package io.bhex.app.trade.presenter;

import android.text.TextUtils;

import java.util.List;

import io.bhex.app.R;
import io.bhex.baselib.constant.AppData;
import io.bhex.baselib.network.Utils.CodeUtils;
import io.bhex.baselib.network.listener.SimpleResponseListener;
import io.bhex.baselib.network.response.ResultResponse;
import io.bhex.baselib.utils.DebugLog;
import io.bhex.baselib.utils.ToastUtils;
import io.bhex.sdk.account.UserInfo;
import io.bhex.sdk.trade.AssetApi;
import io.bhex.sdk.trade.TradeApi;
import io.bhex.sdk.trade.bean.AssetDataResponse;
import io.bhex.sdk.trade.bean.AssetListResponse;
import io.bhex.sdk.trade.bean.CreateOrderRequest;
import io.bhex.sdk.trade.bean.OpenOrderResponse;
import io.bhex.sdk.trade.bean.OrderBean;


public class TradeFragmentPresenter extends BaseTradeFragmentPresenter<TradeFragmentPresenter.TradeFragmentUI> {
    private static final String LOGTAG = "TradeFragmentPresenter";

    public interface TradeFragmentUI extends BaseTradeFragmentPresenter.BaseTradeFragmentUI {

    }
    /**
     * 获取当前委托
     */
    protected void getCurrentEntrustOrders() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        TradeApi.RequestSymbolOpenOrder(getUI().getSymbols(), new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    currentOrders = response.getArray();
                    if (currentOrders != null) {
                        getUI().showOpenOrders(currentOrders);
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    @Override
    public void getHistoryEntrustOrders(final boolean isLoadMore) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        if (isLoadMore) {
            if (historyOrders != null) {
                if (!historyOrders.isEmpty()) {
                    mPageId = historyOrders.get(historyOrders.size() - 1).getOrderId();
                }
            }
        }else{
            mPageId ="";
        }

        String pageId = "";

        if (isLoadMore && !TextUtils.isEmpty(mPageId)) {
            //加载更多
            pageId = mPageId;

        }

        TradeApi.RequestSymbolHistoryEntrustOrders(getUI().getSymbols(), pageId, new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onFinish() {
                super.onFinish();
                if (isLoadMore) {
                    getUI().loadMoreComplete();
                }
            }

            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> data = response.getArray();
                    if (data != null) {

                        if (isLoadMore) {
                            if (data != null) {
                                historyOrders.addAll(data);
                            }

                        } else {
                            if (data != null) {
                                historyOrders.clear();
                                historyOrders = data;
                            }
                        }
                        getUI().showHistoryOrders(historyOrders);

                        if (data.size()< AppData.Config.PAGE_LIMIT) {
                            getUI().loadEnd();
                        }else{
                            getUI().loadMoreComplete();
                        }
                    }else{
                        getUI().loadMoreComplete();
                    }

                }else{
                    getUI().loadMoreFailed();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                if (isLoadMore) {
                    getUI().loadMoreFailed();
                }
            }
        });
    }



    /**
     * 获取资产列表
     * @param token
     */
    protected synchronized void getAssetList(final String token){
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        TradeApi.SubTokenBalanceChange(token,new SimpleResponseListener<AssetListResponse.BalanceBean>() {

            @Override
            public void onSuccess(AssetListResponse.BalanceBean response) {
                super.onSuccess(response);
                if (getUI() == null || !getUI() .isAlive() || response == null)
                    return;
                if (response != null) {
                    getUI().updateAssettByToken(token,response.getFree());
                }else{
                    //因为API接口返回的资产列表，如果没有资产，则没有改币种资产信息，所以为空，代表没有查询到余额 默认按零资产处理
                    getUI().updateAssettByToken(token,"0");
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        });
    }

    protected synchronized void subSymbolOrder() {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }

        TradeApi.SubSymbolOrderChange(getUI().getSymbols(), new SimpleResponseListener<OpenOrderResponse>() {
            @Override
            public void onSuccess(OpenOrderResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    List<OrderBean> srcList = response.getArray();
                    boolean isOrderChange = false;
                    if(srcList != null && srcList.size() > 0) {
                        for (int i = srcList.size() -1; i >= 0 ; i--) {
                            OrderBean srcBean = srcList.get(i);
                            boolean hasSrcBean = false;
                            for (int j = 0; j < currentOrders.size(); j++) {
                                if(srcBean.getOrderId().equalsIgnoreCase(currentOrders.get(j).getOrderId())){
                                    isOrderChange = true;
                                    currentOrders.remove(j);
                                    if(getUI().getSymbols().equals(srcBean.getSymbolId())&&srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                        currentOrders.add(j, srcBean);
                                    hasSrcBean = true;
                                    break;
                                }
                            }
                            if(getUI().getSymbols().equals(srcBean.getSymbolId())&&hasSrcBean == false && srcBean.getStatus() != null && !srcBean.getStatus().equalsIgnoreCase("CANCELED")&& !srcBean.getStatus().equalsIgnoreCase("FILLED"))
                                currentOrders.add(0,srcBean);
                            isOrderChange= true;

                        }
                        if (currentOrders != null&&isOrderChange) {
                            getUI().showOpenOrders(currentOrders);
                        }
                    }


                }
            }
        });

    }

    /**
     * 获取资产
     * @param tokenId
     */
    protected void getAsset(final String tokenId) {
        if (!UserInfo.isLogin()) {
            //未登录状态不请求
            return;
        }
        AssetApi.RequestTokenIdAsset(tokenId,new SimpleResponseListener<AssetDataResponse>(){
            @Override
            public void onFinish() {
                super.onFinish();
            }

            @Override
            public void onSuccess(AssetDataResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response,true)) {
                    List<AssetDataResponse.ArrayBean> data = response.getArray();
                    if (data != null) {
                        if (data.size()>0) {
                            AssetDataResponse.ArrayBean assetBean = data.get(0);
                            if (assetBean != null) {
                                getUI().updateAssettByToken(tokenId,assetBean.getFree());
                            }
                        }
                    }
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
            }
        } );
    }

    /**
     * 下单
     *
     * @param isBuyMode
     * @param isLimitedPrice
     * @param exchangeId
     * @param symbol
     * @param price
     * @param amount
     */
    public void createOrder(boolean isBuyMode, boolean isLimitedPrice, String exchangeId, String symbol, String price, String amount) {

        CreateOrderRequest requestData = new CreateOrderRequest();
        requestData.exchangeId = exchangeId;
        requestData.symbol = symbol;
        requestData.isBuyMode = isBuyMode;
        requestData.isLimitedPrice = isLimitedPrice;
        requestData.price = price;
        requestData.amount = amount;
        TradeApi.RequestCreateOrder(requestData, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    ToastUtils.showShort(getActivity(), getString(R.string.string_create_order_success));
                    getUI().createOrderSuccess();
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_create_order_failed));
            }
        });
    }

    /**
     * 撤销全部订单
     */
    public void revokeAllOrders() {
        if (!UserInfo.isLogin()) {
            return;
        }
        TradeApi.RequestCancelAllOrder(getUI().getSymbols(), new SimpleResponseListener<ResultResponse>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(ResultResponse response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(), getString(R.string.string_submit_revoke_all_orders));
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
            }
        });
    }

    public void cancelOrder(String orderId) {
        TradeApi.RequestCancelOrder(orderId, new SimpleResponseListener<OrderBean>() {
            @Override
            public void onBefore() {
                super.onBefore();
                getUI().showProgressDialog("","");
            }

            @Override
            public void onFinish() {
                super.onFinish();
                getUI().dismissProgressDialog();
            }

            @Override
            public void onSuccess(OrderBean response) {
                super.onSuccess(response);
                if (CodeUtils.isSuccess(response, true)) {
//                    DebugLog.w("Order", "撤单：" + response.isSuccess());
                    ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_success));
                    refreshCurrentOrders();
                }
            }

            @Override
            public void onError(Throwable error) {
                super.onError(error);
                ToastUtils.showShort(getActivity(), getString(R.string.string_revoke_failed));
            }
        });
    }


}